<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="资源列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        default-expand-all
        :single-line="false"
        striped
        class="sm:h-full"
      />
    </NCard>
    <ResourceEditModal v-model:visible="visible" :operate-type="operateType" :row-data="editingData" @submitted="getData"/>
    <ResourceButtonModal v-model:buttonVisible="buttonVisible" :row-data="addButtonData" @submitButton="getData"/>
  </div>
</template>

<script setup lang="tsx">
import { ref} from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm,NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { resourceList,resourceDelete } from '@/service/api/resource-api'
import { useListTable, useTableOperate } from '@/hooks/common/list-table';
import SvgIcon from '@/components/custom/svg-icon.vue';
import {resourceCategoryRecord} from "@/constants/common";
import ResourceEditModal,{type OperateType}  from './modules/resource-edit-modal.vue'
import ResourceButtonModal from './modules/button-modal.vue';

const { bool: visible, setTrue: openModal } = useBoolean();
const { bool: buttonVisible,setTrue: openButtonModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);

const { columns, columnChecks, data, loading, getData } = useListTable({
    apiFn: resourceList,
    columns: () => [
      {
        type: 'selection',
        align: 'center',
        width: 30
      },
      {
        key: 'title',
        title: '资源名称',
        align: 'center',
        width: 80
      },
      {
        key: 'menuType',
        title: '菜单类型',
        align: 'center',
        width: 80,
        render: row => {
          if (row.menuType === null) {
            return null;
          }
          const tagMap: Record<Api.SystemManage.ResourceCategory, NaiveUI.ThemeColor> = {
            CATALOG: 'default',
            MENU: 'primary',
            IFRAME: 'primary',
            LINK: 'primary',
          };

          const label = resourceCategoryRecord[row.menuType];

          return <NTag type={tagMap[row.menuType]}>{label}</NTag>;
        }
      },
      {
        key: 'icon',
        title: '图标',
        align: 'center',
        width: 80,
        render: row => {
          const icon = row.iconType === '1' ? row.icon : undefined;

          const localIcon = row.iconType === '2' ? row.icon : undefined;

          return (
            <div class="flex-center">
              <SvgIcon icon={icon} localIcon={localIcon} class="text-icon"/>
            </div>
          );
        }
      },
      {
        key: 'name',
        title: '路由名称',
        align: 'center',
        width: 100
      },
      {
        key: 'path',
        title: '路由路径',
        align: 'center',
        width: 100
      },
      {
        key: 'component',
        title: '页面组件',
        align: 'center',
        width: 130
      },
      {
        key: 'createUserName',
        title: '创建人',
        align: 'center',
        width: 100
      },
      {
        key: 'createTime',
        title: '创建时间',
        align: 'center',
        width: 100
      },
      {
        key: 'operate',
        title: '操作',
        align: 'center',
        titleAlign:'center',
        width: 100,
        render: row => (
          <div class="flex-center gap-8px">
            <NButton quaternary type="primary" size="small" onClick={() => edit(row.id)}>
              <SvgIcon icon='mdi:lead-pencil' class="text-icon"/>
              编辑
            </NButton>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => '确认删除吗？',
                trigger: () => (
                  <NButton quaternary type="error" size="small">
                    <SvgIcon icon='mdi:delete' class="text-icon"/>
                    删除
                  </NButton>
                )
              }}
            </NPopconfirm>
            {row.menuType === 'MENU' && (
              <NButton quaternary type="success" size="small" onClick={() => addButton(row.id)}>
                <SvgIcon icon='mdi:gesture-tap' class="text-icon"/>
                按钮权限
              </NButton>
            )}
          </div>
        )
      }
    ]
  })
;

const {checkedRowKeys, onBatchDeleted, onDeleted} = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');
// 新增
function handleAdd() {
  operateType.value = 'add';
  openModal();
}
// 批量删除
async function handleBatchDelete() {
  const result: Api.Common.DeleteParams[] = checkedRowKeys.value.map(key => ({id: key}));
  await resourceDelete(result)
  await onBatchDeleted();
}
// 删除
async function handleDelete(id: number) {
  let params: Api.Common.DeleteParams[] = [{id: id}]
  await resourceDelete(params)
  await onDeleted();
}

const editingData: Ref<number | null> = ref(null);
// 编辑
function edit(id:number){
  operateType.value = 'edit';
  editingData.value = id;
  openModal();
}
const addButtonData: Ref<number | null> = ref(null);
// 按钮权限
function addButton(id:number){
  addButtonData.value = id;
  openButtonModal()
}
</script>

<style scoped>

</style>
